package my.servlet.startup;

import my.servlet.connector.HttpConnector;
import my.servlet.core.container.context.Context;
import my.servlet.core.container.context.Mapper;
import my.servlet.core.container.context.SimpleContext;
import my.servlet.core.container.context.SimpleContextMapper;
import my.servlet.core.container.wrapper.StandardWrapper;
import my.servlet.core.container.wrapper.Wrapper;
import my.servlet.core.lifecycle.Lifecycle;
import my.servlet.core.loader.Loader;
import my.servlet.core.loader.SimpleLoader;
import my.servlet.core.pipeline.ClientIPLoggerValve;
import my.servlet.core.pipeline.HeaderLoggerValve;
import my.servlet.core.pipeline.Pipeline;
import my.servlet.core.pipeline.Valve;
import my.servlet.logger.FileLogger;

public final class Bootstrap2 {
    public static void main(String[] args) {
        HttpConnector connector = new HttpConnector();
        Wrapper wrapper1 = new StandardWrapper();
        wrapper1.setName("Primitive");
        wrapper1.setServletClass("my.servlet.webroot.PrimitiveServlet");
        Wrapper wrapper2 = new StandardWrapper();
        wrapper2.setName("Modern");
        wrapper2.setServletClass("my.servlet.webroot.ModernServlet");

        Context context = new SimpleContext();
        context.addChild(wrapper1);
        context.addChild(wrapper2);

        Valve valve1 = new HeaderLoggerValve();
        Valve valve2 = new ClientIPLoggerValve();

        ((Pipeline) context).addValve(valve1);
        ((Pipeline) context).addValve(valve2);

        Mapper mapper = new SimpleContextMapper();
        mapper.setProtocol("http");
        context.addMapper(mapper);
        Loader loader = new SimpleLoader();
        context.setLoader(loader);
        context.addServletMapping("/Primitive", "Primitive");
        context.addServletMapping("/Modern", "Modern");

        System.setProperty("servlet.log.base", System.getProperty("user.dir"));
        FileLogger logger = new FileLogger();
        logger.setPrefix("FileLog_");
        logger.setSuffix(".txt");
        logger.setTimestamp(true);
        logger.setDirectory("webroot");
        context.setLogger(logger);

        connector.setContainer(context);
        try {
            connector.initialize();
            connector.start();

            ((Lifecycle) context).start();

            // make the application wait until we press a key.
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}